<template>
  <div class="loginWrapper">
    <div class="header">
      <span>微信</span>
      <div class="op">
        <div class="opIcon"><SettingOutlined :style="{ fontSize: '13px' }" /></div>
        <div class="opIcon danger"><CloseOutlined :style="{ fontSize: '13px' }" @click="closeWindow" /></div>
      </div>
    </div>
    <div class="loginContainer">
      <span class="tipCode">{{ loginModel == 0 ? '扫码登录' : '账号密码登录' }}</span>
      <div class="catpchaWrapper" v-if="loginModel == 0">
        <img :src="qrUrl" @click="initQrCode" />
      </div>
      <div class="formWrapper" v-else>
        <div class='formItem'>
          <Input :class="{error: accountEmpty}" class="loginItem" v-model:value="formData.account" placeholder="请输入您的账号" />
          <div class='errTip' v-if="accountEmpty">账号不能为空</div>
        </div>
        <div class='formItem'>
          <Input type="password" :class="{error: passwordEmpty}" class="loginItem" v-model:value="formData.password" placeholder="请输入您的密码" @keydown.enter="doLogin"/>
          <div class='errTip' v-if="passwordEmpty">密码不能为空</div>
        </div>
        <Button type="primary" class="loginBtn" @click="doLogin" :loading="loginLoading"
          >登录</Button
        >
      </div>
    </div>
    <div class="tipBottom" @click="changeLoginModel">
      {{ loginModel == 0 ? '账号密码登录' : '扫码登录' }}
    </div>
  </div>
</template>
<script lang="ts">
import { SettingOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { defineComponent, onMounted } from 'vue'
import { Input, Button, message } from 'ant-design-vue'
import QRCode from 'qrcode'
import { ref, reactive } from 'vue'
import Base64Util from '@/utils/Base64Util'
import { LoginSuccess } from '@/utils/Electron'
import { login } from '@/lib/api'
import useAuthStore from "@/stores/authStore"
// import { ipcRenderer } from 'electron'

export default defineComponent({
  name: 'login-page',
  setup() {
    // store
    const authStore = useAuthStore()
    // 属性
    let qrUrl = ref<String>('')
    let qrValue = ref<String>('暂未开通，请使用账号密码登录')
    let loginModel = ref<Number>(0) //0是扫码登录
    let loginLoading = ref<Boolean>(false)
    let formData = ref({
      account: '',
      password: ''
    })
    let user = ref('')
    let accountEmpty = ref<Boolean>(false)
    let passwordEmpty = ref<Boolean>(false)

    // 方法
    const initQrCode = () => {
      qrValue.value += new Date().getTime()
      QRCode.toDataURL(qrValue.value)
        .then((url) => {
          qrUrl.value = url
        })
        .catch((err) => {
          console.error(err)
        })
    }
    // 关闭应用
    const closeWindow = () => {
      electron.handleSend({ type: 'closed' })
    }
    // 修改登录模式
    const changeLoginModel = () => {
      loginModel.value = loginModel.value == 0 ? 1 : 0
    }
    // 校验
    const validte = () => {
      return new Promise((resolve, reject)=> {
        let hasErr = false
        if (formData.account == '') {
          hasErr = true
          accountEmpty.value = true
          setTimeout(()=> {
            accountEmpty.value = false
          }, 1000)
        }
        if (formData.password == '') {
          hasErr = true
          passwordEmpty.value = true
          setTimeout(()=> {
            passwordEmpty.value = false
          }, 1000)
        }
        if(!hasErr) {
          resolve(1)
        }
      })
    }
    /**
     * Handles the login process by encoding the account and password, setting various local storage items,
     * and notifying the main application window of a successful login via Electron's inter-process communication.
     * @function doLogin
     */
    // 登录方法
    const doLogin = () => {
      // 将账号和密码进行拼接 _ 然后base64加密 作为token
      validte().then(()=> {
        loginLoading.value = true
        login({ username: formData.value.account, password: formData.value.password }).then((res) => {
          loginLoading.value = false
          if (res.code === 0) {
            loginLoading.value = false
            authStore.token = res.data.token
            authStore.userInfo = res.data.userInfo
            authStore.momentInfo = res.data.momentInfo
            // 同步数据
            authStore.stateSync()
            // 关闭登录窗口，打开主窗口
            LoginSuccess()
          }
        })
      })
    }
    // 初始化事件
    onMounted(() => {
      initQrCode()
      window.api.on('main-render-dom', (eventA: any, msg: any) => {
        loginModel.value = 0
        formData.value.account = ''
        formData.value.password = ''

      }); 
    })
    return {
      qrValue,
      qrUrl,
      formData,
      loginLoading,
      accountEmpty,
      passwordEmpty,
      user,
      loginModel, // 属性
      initQrCode,
      closeWindow,
      doLogin,
      changeLoginModel // 事件
    }
  },
  components: {
    SettingOutlined,
    CloseOutlined,
    Input,
    Button
  }
})
</script>
<style lang="less" scoped>
.loginWrapper {
  background-image: url('~@/assets/images/login-bg.jpg') 100% 100% no-repeat;
  height: 365px;
  width: 100%;
  position: relative;
  user-select: none;
  -webkit-app-region: no-drag;
  .header {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    > span {
      line-height: 1;
      color: #a3a3a3;
      font-size: 14px;
    }
    .op {
      display: flex;
      position: absolute;
      right: 0;
      top: 0;
      .opIcon {
        width: 35px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        &.danger:hover {
          background-color: red;
          color: white;
        }
      }
    }
  }
  .loginContainer {
    padding: 20px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    .tipCode {
      color: #06c580;
      font-size: 16px;
      margin-top: 4px;
    }
    .catpchaWrapper {
      width: 100%;
      text-align: center;
      img {
        width: 90%;
      }
    }
    .formWrapper {
      margin-top: 20px;
      width: 100%;
      .formItem {
        margin-top: 10px;
        height: 45px;
        .errTip {
          font-size: 12px;
          color: red;
          margin-top: 2px;
        }
        .error {
          border: 1px solid red;
        }
      }
      button {
        margin-top: 30px;
        width: 100%;
        -webkit-app-region: no-drag;
      }
    }
  }
  .tipBottom {
    position: absolute;
    bottom: 8%;
    width: 50%;
    left: 50%;
    transform: translate(-50%, 0);
    color: #454f87;
    text-align: center;
    cursor: pointer;
    font-size: 14px;
  }
}
</style>
